import { useStore } from '@/hooks';
import { Dialog, Form, Input, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';

const CancelCarDrawer = (props) => {
  const { visible, onClose, task } = props;
  const { ccTaskStore: store } = useStore();
  const [formData, setFormData] = useState({});
  const editCtx = useRef({ origin: {}, changed: {} }).current;

  useEffect(() => {
    editCtx.changed = {};
    setFormData({});
  }, [task]);

  const onSubmitCancelRemark = async (result) => {
    _.assign(result, { taskId: task.id, way: 1 });
    if (!_.isEmpty(result)) {
      try {
        await store.cancelSendCar(result);
        Message.success({ content: t`取消派车成功` });
      } catch (e) {
        Message.error({ content: t`取消派车失败!${e.source?.message}`, duration: 7000 });
        throw e;
      }
    }
    onClose?.();
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);
    setFormData({ ...formData });

    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    if (!_.isEmpty(editCtx.changed)) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => {
          onClose?.();
        },
      });
      return;
    }
    onClose?.();
  };

  return (
    <Dialog
      visible={visible}
      title={t`确认取消当前司机?`}
      onClose={handleCancel}
      v2
      onOk={() => onSubmitCancelRemark(formData)}
    >
      <Form
        value={formData}
        onChange={handleChange}
      >
        <Form.Item >
          <Input.TextArea
            name="remark"
            placeholder={t`请输入取消原因`}
          />
        </Form.Item>
      </Form>
    </Dialog>
  );
};

export default observer(CancelCarDrawer);
